<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service;

use app\enum\CommandEnum;
use app\enum\CommonEnum;
use app\model\ClientAccountModel;
use app\model\KsAdvertiserModel;
use think\facade\Cache;

class ImplementTaskService
{
    /**
     * 生成redis序列.
     */
    public static function setAdvIdsForTask()
    {
        try {
            $redis = Cache::store('redis')->handler();
            $advertiser_list_num = env('task_config.QUEUE_LENGTH');
            // 获取队列的key
            $oeTaskKeys = array_values(CommandEnum::OE_TASK_LIST_KEY);
            // 快手队列的key
            $ksTaskKeys = array_values(CommandEnum::KS_TASK_LIST_KEY);
            // 快手user-id分组队列的key
            $ksUserTaskKeys = array_values(CommandEnum::KS_USER_TASK_LIST_KEY);
            // 广点通队列的key
            $qqTaskKeys = array_values(CommandEnum::QQ_TASK_LIST_KEY);
            $need_add = [];

            // 腾讯-广点通
            if ($qqTaskKeys) {
                $qqAdvertiserIds = self::_getAccount(CommonEnum::QQ_MEDIA);
                $qq_num = ! empty($qqAdvertiserIds) ? count($qqAdvertiserIds) : 0;
                $qq_number = min([$qq_num, $qq_num * 3]);
                foreach ($qqTaskKeys as $rediskey) {
                    if ($redis->lLen($rediskey) < $qq_number) {
                        foreach ($qqAdvertiserIds as $advertiserId) {
                            if (array_key_exists($rediskey, $need_add)) {
                                if (! in_array($advertiserId, $need_add[$rediskey]['redis_key'])) {
                                    $need_add[$rediskey]['redis_key'][] = $advertiserId;
                                }
                            } else {
                                $need_add[$rediskey] = [];
                                $need_add[$rediskey]['redis_key'] = [];
                                $need_add[$rediskey]['redis_key'][] = $advertiserId;
                            }
                        }
                    }
                }
            }

            // 巨量
            if ($oeTaskKeys) {
                $oeAdvertiserIds = self::_getAccount(CommonEnum::OE_MEDIA);
                $oe_num = ! empty($oeAdvertiserIds) ? count($oeAdvertiserIds) : 0;
                $oe_number = min([$oe_num, $advertiser_list_num]);
                foreach ($oeTaskKeys as $rediskey) {
                    if ($redis->lLen($rediskey) < $oe_number) {
                        // 存储巨量所有广告主信息队列
                        foreach ($oeAdvertiserIds as $advertiserId) {
                            if (strpos($advertiserId, '_del') !== false) {
                                continue;
                            }
                            if (array_key_exists($rediskey, $need_add)) {
                                if (! in_array($advertiserId, $need_add[$rediskey]['redis_key'])) {
                                    $need_add[$rediskey]['redis_key'][] = $advertiserId;
                                }
                            } else {
                                $need_add[$rediskey] = [];
                                $need_add[$rediskey]['redis_key'] = [];
                                $need_add[$rediskey]['redis_key'][] = $advertiserId;
                            }
                        }
                    }
                }
            }
            // 快手
            if ($ksTaskKeys) {
                $ksAdvertiserIds = self::_getAccount(CommonEnum::KS_MEDIA);
                $ks_num = ! empty($ksAdvertiserIds) ? count($ksAdvertiserIds) : 0;
                $k_number = min([$ks_num, $advertiser_list_num]);
                foreach ($ksTaskKeys as $rediskey) {
                    if ($redis->lLen($rediskey) < $k_number) {
                        foreach ($ksAdvertiserIds as $advertiserId) {
                            if (strpos($advertiserId, '_del') !== false) {
                                continue;
                            }
                            if (array_key_exists($rediskey, $need_add)) {
                                if (! in_array($advertiserId, $need_add[$rediskey]['redis_key'])) {
                                    $need_add[$rediskey]['redis_key'][] = $advertiserId;
                                }
                            } else {
                                $need_add[$rediskey] = [];
                                $need_add[$rediskey]['redis_key'] = [];
                                $need_add[$rediskey]['redis_key'][] = $advertiserId;
                            }
                        }
                    }
                }
            }
            // 快手user
            if ($ksUserTaskKeys) {
                $ksAdvertiserIds = self::_getKsUserAccount();
                $ks_num = ! empty($ksAdvertiserIds) ? count($ksAdvertiserIds) : 0;
                $k_number = min([$ks_num, $advertiser_list_num]);
                foreach ($ksUserTaskKeys as $rediskey) {
                    if ($redis->lLen($rediskey) < $k_number) {
                        foreach ($ksAdvertiserIds as $advertiserId) {
                            if (array_key_exists($rediskey, $need_add)) {
                                if (! in_array($advertiserId, $need_add[$rediskey]['redis_key'])) {
                                    $need_add[$rediskey]['redis_key'][] = $advertiserId;
                                }
                            } else {
                                $need_add[$rediskey] = [];
                                $need_add[$rediskey]['redis_key'] = [];
                                $need_add[$rediskey]['redis_key'][] = $advertiserId;
                            }
                        }
                    }
                }
            }
            // 腾讯-广点通
            if ($qqTaskKeys) {
                $qqAdvertiserIds = self::_getAccount(CommonEnum::QQ_MEDIA);
                $qq_num = ! empty($qqAdvertiserIds) ? count($qqAdvertiserIds) : 0;
                $qq_number = min([$qq_num, $qq_num * 3]);
                foreach ($qqTaskKeys as $rediskey) {
                    if ($redis->lLen($rediskey) < $qq_number) {
                        foreach ($qqAdvertiserIds as $advertiserId) {
                            if (array_key_exists($rediskey, $need_add)) {
                                if (! in_array($advertiserId, $need_add[$rediskey]['redis_key'])) {
                                    $need_add[$rediskey]['redis_key'][] = $advertiserId;
                                }
                            } else {
                                $need_add[$rediskey] = [];
                                $need_add[$rediskey]['redis_key'] = [];
                                $need_add[$rediskey]['redis_key'][] = $advertiserId;
                            }
                        }
                    }
                }
            }
            foreach ($need_add as $taskkey => $need_a) {
                foreach ($need_a['redis_key'] as $vale) {
                    $redis->rPush($taskkey, $vale);
                }
            }
        } catch (\Exception $e) {
            dump($e);
        }
    }

    /**
     * 获取正常账户.
     */
    private static function _getAccount(int $mediaId = 0): array
    {
        return ClientAccountModel::where('media_id', $mediaId)
            ->where('auth_valid', 1)
            ->order('cost_sort desc,id desc')
            ->column('advertiser_id');
    }

    /**
     * 获取快手user正常账户.
     */
    private static function _getKsUserAccount(): array
    {
        //        return KsAdvertiserModel::alias('a')
        //            ->join(['habo_client_account' => 'b', 'a.advertiser_id=b.advertiser_id'])
        //            ->where('b.auth_valid', 1)
        //            ->group('a.user_id')
        //            ->order('b.id desc')
        //            ->column('b.advertiser_id');
        return KsAdvertiserModel::where('auth_valid', 1)
            ->group('user_id')
            ->order('id desc')
            ->column('advertiser_id');
    }
}
